import modelExtend from 'dva-model-extend'
import api from 'api'
import { pageModel } from 'utils/model'
const { pathToRegexp } = require("path-to-regexp")
const { queryLotProductList, updateLotProduct, createLotProduct,deleteLotProduct,queryLotModelOptions } = api

export default modelExtend(pageModel, {
  namespace: 'lot_product',

  state: {
    lotModelOptions: [], //模型选项
    mapModel: {}
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if (pathToRegexp('/lot_product').exec(location.pathname)) {
          dispatch({
            type: 'query',
            payload: {
              pageSize: 20,
              pageNum: 1,
              // status: 2,
              ...location.query,
            },
          })

          dispatch({
            type: 'queryLotModelOptions',
            payload: {}
          })

        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {
      const data = yield call(queryLotProductList, payload)
      if (data.success) {
        yield put({
          type: 'querySuccess',
          payload: {
            list: data.payload.list,
            pagination: {
              current: Number(payload.pageNum) || 1,
              pageSize: Number(payload.pageSize) || 10,
              total: data.total,
            },
          },
        })
      } else {
        throw data
      }
    },
    *queryLotModelOptions({payload}, {call, put}) {
      const data = yield call(queryLotModelOptions, {});
      if(data.success) {
        let mapModel = {}
        const options = data.payload.list.map(value => {
          mapModel[value.id] = value.name;
          return {value:value.id, label: value.name}
        })
        yield  put({
          type: 'updateState',
          payload: {
            lotModelOptions: options,
            mapModel: mapModel
          }
        })
      }
    },
   *create({ payload }, { call, put }) {
      const data = yield call(createLotProduct, payload)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },

    *update({ payload }, { select, call, put }) {
      const newUser = { ...payload }
      const data = yield call(updateLotProduct, newUser)
      if (data.success) {
        yield put({ type: 'hideModal' })
      } else {
        throw data
      }
    },
    *delete({ payload }, { select, call, put }) {
      const data = yield call(deleteLotProduct, {ids:payload})
      if (!data.success) {
        throw data
      }
    }
  },
  reducers: {
    showModal(state, { payload }) {
      return { ...state, ...payload, modalVisible: true }
    },

    hideModal(state) {
      return { ...state, modalVisible: false }
    },
  },
})
